package dao

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"grpc_demo/conf"
	"strings"
	"time"
)

var DBClient *gorm.DB

// InitGorm 初始化数据库引擎
func InitGorm() error {
	db, err := NewDB()
	if err != nil {
		return err
	}
	DBClient = db
	return nil
}

// NewDB 创建 DBClient 实例
func NewDB() (*gorm.DB, error) {
	c := conf.ConfigInstance.MysqlConf
	cGorm := conf.ConfigInstance.GormConf

	db, err := gorm.Open(mysql.Open(c.DSN()), &gorm.Config{})
	if err != nil {
		return nil, err
	}

	if strings.ToLower(cGorm.Debug) == "true" {
		db = db.Debug()
	}

	sql, _ := db.DB()
	err = sql.Ping()
	if err != nil {
		return nil, err
	}

	sql.SetMaxIdleConns(cGorm.MaxIdleConns)
	sql.SetMaxOpenConns(cGorm.MaxOpenConns)
	sql.SetConnMaxLifetime(time.Duration(cGorm.MaxLifetime) * time.Second)

	return db, nil
}
